<?php

declare(strict_types=1);

namespace App\Common\Redis;

use Hyperf\Cache\CacheManager;
use Hyperf\Context\ApplicationContext;
use Psr\SimpleCache\CacheInterface;


class TaggedCache
{
    protected CacheInterface $cache;

    public function __construct()
    {
        $this->cache = ApplicationContext::getContainer()->get(CacheInterface::class);
    }

    /**
     * 设置带标签的缓存
     */
    public function setWithTags(string $key, $value, array $tags, ?int $ttl = null): bool
    {
        // 存储缓存
        $this->cache->set($key, $value, $ttl);
        // 关联标签
        foreach ($tags as $tag) {
            $this->cache->addKey(
                $this->getTagKey($tag),
                $key
            );
        }

        return true;
    }

    /**
     * 通过标签获取缓存
     */
    public function getByTag(string $tag): array
    {
        $keys = $this->getTagKeys($tag);
        return $this->cache->getMultiple($keys);
    }

    /**
     * 清除标签关联的所有缓存
     */
    public function flushTag(string $tag): bool
    {
        $keys = $this->getTagKeys($tag);

        // 删除缓存项
        if(!empty($keys)){
            $this->cache->deleteMultiple($keys);
        }

        // 删除标签记录
        $this->cache->delete(
            $this->getTagKey($tag)
        );

        return true;
    }

    /**
     * 获取标签关联的所有缓存键
     */
    private function getTagKeys(string $tag): array
    {
        return $this->cache->keys(
            $this->getTagKey($tag)
        ) ?: [];
    }

    /**
     * 获取标签存储键
     */
    private function getTagKey(string $tag): string
    {
        return config('cache.default.prefix', 'hyperf:cache:') . '{tags}:' . $tag;
    }
}